/*
 * Copyright (C) 2020-2023. Huawei Technologies Co., Ltd. All rights reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.boostkit.omniadvisor;

import com.huawei.boostkit.omniadvisor.exception.OmniAdvisorException;
import com.huawei.boostkit.omniadvisor.executor.OmniAdvisorRunner;
import org.apache.commons.lang.time.DateUtils;

import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public final class OmniAdvisor {
    private static final int REQUIRED_PARAMS_LENGTH = 4;
    private static final String[] TIME_PARSE_PATTERNS = {"yyyy-MM-dd HH:mm:ss"};

    private OmniAdvisor() {}

    public static void main(String[] args) {
        List<String> params = removeEmptyArgs(args);

        if (params.size() != REQUIRED_PARAMS_LENGTH) {
            throw new OmniAdvisorException("The number of parameters is abnormal. Only four parameters are supported.");
        }

        Date startDate;
        Date finishDate;
        try {
            startDate = DateUtils.parseDate(params.get(0), TIME_PARSE_PATTERNS);
            finishDate = DateUtils.parseDate(params.get(1), TIME_PARSE_PATTERNS);
        } catch (ParseException e) {
            throw new OmniAdvisorException("Unsupported date format. Only the 'yyyy-MM-dd HH:mm:ss' is supported", e);
        }

        long startTimeMills = startDate.getTime();
        long finishedTimeMills = finishDate.getTime();

        if (startTimeMills > finishedTimeMills) {
            throw new OmniAdvisorException("start time cannot be greater than finish time");
        }

        OmniAdvisorContext.initContext(params.get(2), params.get(3));
        OmniAdvisorRunner runner = new OmniAdvisorRunner(startTimeMills, finishedTimeMills);
        runner.run();
    }

    private static List<String> removeEmptyArgs(String[] args) {
        return Arrays.stream(args).filter(arg -> !arg.isEmpty()).collect(Collectors.toList());
    }
}
